package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @author HUANGLX
 * @version 1.0
 * @description TODO
 * @date 2024/2/19 10:01
 */
@Service
public class UserServiceImpl implements UserService {
    public static final String wx_login="https://api.weixin.qq.com/sns/jscode2session";
    public static final String authorization_code="authorization_code";


    @Autowired
    public WeChatProperties wechatProperties;//封装yml配置的微信信息
    @Autowired
    public UserMapper userMapper;

    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
        String openid = getOpenId(userLoginDTO.getCode());
        if (openid==null){
          throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //判断这个用户是不是系统的新用户
        User user = userMapper.getUserByOpenid(openid);
        if (user==null){
            //是的话构建对象然后保存到数据库，自动完成注册
            user =  User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now()).build();
            userMapper.insert(user);
        }
        return user;
    }


    /***
    * 调用微信的接口服务获取用户的openid
    */
    private String getOpenId(String code){
        //调用微信接口服务获得当前用户的openId 用http的doGet方法
        Map<String,String> paramMap = new HashMap<>();
        paramMap.put("appid",wechatProperties.getAppid());
        paramMap.put("secret",wechatProperties.getSecret());
        paramMap.put("js_code",code);
        paramMap.put("grant_type",authorization_code);
        String json = HttpClientUtil.doGet(wx_login, paramMap);
        //获得到的数据根据key解析
        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");
        return openid;
    }
}
